package com.hivis.controller;

import com.alibaba.fastjson.JSON;
import com.hivis.utils.TokenUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/token")
public class TokenController {
    //获取AccessToken
    @ResponseBody
    @RequestMapping(value = "gettoken", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public String gettoken(String secret, String account, HttpServletRequest request) {
        Map<String, Object> ack = createToken(secret, account);

        return JSON.toJSONString(ack);
    }

    private Map<String, Object> createToken(String secret, String account) {
        Map<String, Object> ack = new HashMap<>();

        if (!StringUtils.isEmpty(secret)) {
            Map<String, String> claims = new HashMap<>();
            claims.put("account", account);
//            claims.put("secret", secret);
            // 生成token
            String token = TokenUtil.createToken(claims);
            if (!StringUtils.isEmpty(token)) {
                ack.put("code", 0);
                ack.put("access_token", token);
                ack.put("expires_in", 7200);

            } else {
                ack.put("errcode", 1002);
                ack.put("errText", "create token exception");
            }
        } else {
            ack.put("errcode", 1000);
            ack.put("errText", "secret can not be empty");
        }
        return ack;
    }
}
